package com.webserver.core;

import com.webserver.http.EmptyRequestException;
import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;
import com.webserver.servlet.DispatcherServlet;

import java.io.*;
import java.net.Socket;

/**
 * 用于处理客户端的交互
 * 遵循HTTP协议与客户端的交互规则为一问一答,因此这里处理分为三步:
 * 1.解析请求
 * 2.处理请求
 * 3.响应客户端
 * 断开连接.
 */
public class ClientHandler implements Runnable {
    private Socket socket;

    public ClientHandler(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try {
            //第一步:解析请求
            HttpRequest request = new HttpRequest(socket);
            HttpResponse response = new HttpResponse(socket);

            //第二步:处理请求
            DispatcherServlet servlet = new DispatcherServlet();
            servlet.service(request,response);

            //第三步:响应客户端
            response.flush();

            System.out.println("响应发送完毕");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (EmptyRequestException e) {
            //空请求什么都不用处理,目的是忽略上面的2,3步操作
        } finally {
            //交互完毕后断开连接(协议要求)
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}